package extractors;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import parser.ArticleParser;
import primitive.Article;
import primitive.Pair;

public class TriGram implements SimilarityMeasure {
	
	private List<Article> training_data;	// Needed by interface
	
	private ArticleParser parser = new ArticleParser();

	@Override
	public double similarity(Article art1, Article art2) {
		String s1 = parser.remove_all(art1).getBody();
		String s2 = parser.remove_all(art2).getBody();
		
		double s = compare_sentence(s1, s2);
		return s;
	}

	
	// -------------------------- Out of interface -------------------------------------
	
	public double compare_sentence(String s1, String s2) {
		String[] w1 = s1.split(" ");
		String[] w2 = s2.split(" ");
		
		double sume = 0.0;
		double max = 0.0;
		
		for (int i = 0; i < w1.length; ++i) {
			max = 0.0;
			for (int j = 0; j < w2.length; ++j) {
				double a = sim(w1[i], w2[j]);
				if (a > max) {
					max = a;
				}
				//System.out.println(w1[i] + " & " + w2[j] + " => " + a);
			}
			sume += max;
		}
		
		//System.out.println(sume + " " + sume / w1.length);
		
		return sume / w1.length;
	}
	
	private double sim(String s1, String s2) {
		double n = 0;
		double counter = 0;
		
		String longer = "";
		String shorter = "";
		
		// We need to chose longer word as this one from which substrings gonna be taken
		if (s1.length() > s2.length()) {
			longer = s1;
			shorter = s2;
		} else {
			longer = s2;
			shorter = s1;
		}
		
		n = longer.length() - 2;
		
		for (int i = 0; i+3 <= longer.length(); ++i) {
			String ngram = longer.substring(i, i+3);
			
			if (shorter.contains(ngram)) {
				counter++;
			}
		}
		
		return counter / n;
	}


	@Override
	public void setTrainingData(List<Article> trainingData) {
		training_data = trainingData;
		
	}


	@Override
	public List<Article> getTrainingData() {
		return training_data;
	}
	
}
